<template>
  <div class="add-purchase-order-wrap">
    <div class="header">采购下单</div>
    <div class="add-purchase-order-con">
      <div class="flex-c" style="margin-bottom: 10px">
        <p>注意：此处填写的采购税率和单价会直接体现在交货单上，也是采购单请款的价格</p>
        <p style="margin-left: 20px"><span class="warningColor">*</span>采购员：</p>
        <a-select v-model="purchaseUser" value-key="id" style="width: 120px" placeholder="" allow-search>
          <a-option v-for="(user, index) in userList" :key="index" :value="user">{{ user.userName }}</a-option>
        </a-select>
      </div>
      <a-table
        class="table-two-line show-border-table"
        style="flex: 1"
        ref="tableRef"
        row-key="id"
        :loading="tableLoading"
        :data="purchaseItems"
        :scroll="{
          x: '100%',
          y: '100%',
        }"
        :span-method="spanMethodAll"
        size="mini"
        :pagination="false"
      >
        <template #columns>
          <a-table-column data-index="shop" title="采购计划" :width="110" fixed="left">
            <template #cell="{ record }">
              <a-space>
                <p class="highlight">{{ record.planNo }}</p>
                <span v-if="record.urgent" class="urgent">急</span>
              </a-space>
            </template>
          </a-table-column>
          <a-table-column data-index="shopName" title="店铺" :width="120" fixed="left">
            <template #cell="{ record }">
              <TextLimit :val="record.shopName" />
            </template>
          </a-table-column>
          <a-table-column data-index="img" title="图片" :width="60" fixed="left">
            <template #cell="{ record }">
              <ImgPopover :src="record.productImg">
                <template #con>
                  <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                </template>
              </ImgPopover>
            </template>
          </a-table-column>
          <a-table-column title="产品名称" :width="100">
            <template #cell="{ record }">
              <TextLimit :val="record.productName" />
            </template>
          </a-table-column>

          <a-table-column data-index="sku" title="SKU/类目" :width="120">
            <template #cell="{ record }">
              <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
              <p>{{ record.cateName || '--' }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="msku" title="MSKU/ASIN" :width="120">
            <template #cell="{ record }">
              <TextLimit :val="record.msku || '--'" :rows="1" />
              <TextLimit :val="record.asin || '--'" :rows="1" />
            </template>
          </a-table-column>
          <a-table-column data-index="productSpecs" title="SKU规格" :width="100">
            <template #cell="{ record }">
              <TextLimit :val="getProductSpecs(record)" />
            </template>
          </a-table-column>
          <a-table-column title="目的仓" :width="120">
            <template #cell="{ record }">
              <p>{{ record.warehouseName }}({{ record.warehouseCode }})</p>
            </template>
          </a-table-column>
          <a-table-column title="计划交期" :width="90">
            <template #cell="{ record }">
              <p>{{ $setTime(record.gmtPlanDelivery, 'YYYY/MM/DD') }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="purchaseStayAmt" title="待采购量" :width="70" />
          <a-table-column data-index="supplier" :width="190">
            <template #title>
              <a-space>
                <p>
                  <span class="warningColor">*</span>
                  <span>供应商</span>
                </p>
                <a-popconfirm @popup-visible-change="globalSupplier = null" @ok="updateSupplier">
                  <template #content>
                    <a-select v-model="globalSupplier" value-key="id" allow-search style="width: 150px" placeholder="选择供应商">
                      <a-option v-for="(supplier, index) in supplierList" :key="index" :value="supplier">{{ supplier.supplierCode }}-{{ supplier.supplierName }}</a-option>
                    </a-select>
                  </template>
                  <p class="highlight cursor">一键设置</p>
                </a-popconfirm>
              </a-space>
            </template>
            <template #cell="{ record, rowIndex }">
              <div class="child-w flex-c" v-for="(item, i) in record.childs" :key="i">
                <!-- 供应商选择 -->
                <div class="cell flex-c" style="width: 182px">
                  <a-select v-model="item.supplier" value-key="id" style="width: 150px" allow-search placeholder="选择供应商" @change="setDefaultPrice(item)">
                    <a-option v-for="(supplier, index) in supplierList" :key="index" :value="supplier">{{ supplier.supplierCode }}-{{ supplier.supplierName }}</a-option>
                  </a-select>
                  <icon-plus-circle class="edit-icon highlight" v-if="i == 0" @click="record.childs.push({ moq: 1, sku: record.sku, settleType: 1 })" />
                  <icon-minus-circle v-else class="edit-icon highlight" @click="record.childs.splice(i, 1)" />
                </div>
                <!-- 起订量 -->
                <div class="cell" style="width: 60px">
                  <p>{{ item.moq }}</p>
                </div>
                <!-- 结算方式 -->
                <div class="cell flex-c" style="width: 120px">
                  <a-select v-model="item.settleType" style="width: 75px">
                    <a-option :value="1">现结</a-option>
                    <a-option :value="2">月结</a-option>
                  </a-select>
                  <icon-double-down v-if="!(rowIndex === purchaseItems.length - 1 && i === record.childs.length - 1)" class="edit-icon" @click="setGlobal(item, 'settleType', i, rowIndex)" />
                </div>
                <!-- 预计交期 -->
                <div class="cell flex-c" style="width: 160px">
                  <a-date-picker v-model="item.gmtPlanDelivery" style="width: 120px" :disabledDate="(current: any) => dayjs(current).isBefore(dayjs())" />
                  <icon-double-down v-if="!(rowIndex === purchaseItems.length - 1 && i === record.childs.length - 1)" class="edit-icon" @click="setGlobal(item, 'gmtPlanDelivery', i, rowIndex)" />
                </div>
                <!-- 采购量 -->
                <div class="cell flex-c" style="width: 140px">
                  <a-input-number :min="1" :max="record.purchaseStayAmt" @change="setDefaultPrice(item)" :precision="0" v-model="item.purchaseAmt" style="width: 90px" placeholder="" />
                  <icon-double-down v-if="!(rowIndex === purchaseItems.length - 1 && i === record.childs.length - 1)" class="edit-icon" @click="setGlobal(item, 'purchaseAmt', i, rowIndex)" />
                </div>
                <!-- 税率 -->
                <div class="cell flex-c" style="width: 150px">
                  <div>
                    <a-input-number v-model="item.rate" :min="0" :max="100" style="width: 90px" placeholder="" :precision="2" />
                    <span>%</span>
                  </div>
                  <icon-double-down v-if="!(rowIndex === purchaseItems.length - 1 && i === record.childs.length - 1)" class="edit-icon" @click="setGlobal(item, 'rate', i, rowIndex)" />
                </div>
                <!-- 价格 -->
                <div class="cell flex-c" style="width: 150px">
                  <div>
                    <span>￥</span>
                    <a-input-number v-model="item.price" :min="0" style="width: 90px" :precision="2" placeholder="" />
                  </div>
                  <icon-double-down v-if="!(rowIndex === purchaseItems.length - 1 && i === record.childs.length - 1)" class="edit-icon" @click="setGlobal(item, 'price', i, rowIndex)" />
                </div>
                <!-- 采购金额 -->
                <div class="cell" style="width: 80px">
                  <p class="price-type highlight">{{ priceType === 1 ? '含税' : '不含税' }}</p>
                  <p>
                    <span>￥</span>
                    <span>{{ ((item.price || 0) * (item.purchaseAmt || 0)).toFixed(2) }}</span>
                  </p>
                </div>
                <!-- 单价工费 -->
                <div class="cell flex-c" style="width: 150px">
                  <div>
                    <span>￥</span>
                    <a-input-number v-model="item.singleLaborCosts" :min="0" style="width: 90px" placeholder="" :precision="2" />
                  </div>
                  <icon-double-down v-if="!(rowIndex === purchaseItems.length - 1 && i === record.childs.length - 1)" class="edit-icon" @click="setGlobal(item, 'singleLaborCosts', i, rowIndex)" />
                </div>
                <!-- 单件成本 -->
                <div class="cell" style="width: 80px">
                  <span>￥</span>
                  <span>{{ ((item.singleLaborCosts || 0) + (item.price || 0)).toFixed(2) }}</span>
                </div>
                <!-- 合计成本 -->
                <div class="cell" style="width: 80px">
                  <span>￥</span>
                  <span>{{ (((item.singleLaborCosts || 0) + (item.price || 0)) * (item.purchaseAmt || 0)).toFixed(2) }}</span>
                </div>
                <!-- 销售员 -->
                <div class="cell" style="width: 70px">
                  <span>{{ record.salesmanName }}</span>
                </div>
                <!-- 备注 -->
                <div class="cell flex-c" style="width: 150px">
                  <a-input v-model="item.remark" style="width: 90px" placeholder="" />
                  <icon-double-down v-if="!(rowIndex === purchaseItems.length - 1 && i === record.childs.length - 1)" class="edit-icon" @click="setGlobal(item, 'remark', i, rowIndex)" />
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column data-index="deliveryAmt" title="起订量" :width="60" />
          <a-table-column data-index="settleType" title="结算方式" :width="120" />
          <a-table-column title="预计交期" :width="160">
            <template #title>
              <p>
                <span class="warningColor">*</span>
                <span>预计交期</span>
              </p>
            </template>
            <template #cell="{ record }">
              <a-date-picker v-model="record.gmtPlanDelivery" style="width: 120px" :disabledDate="(current: any) => dayjs(current).isBefore(dayjs())" />
            </template>
          </a-table-column>
          <a-table-column data-index="purchaseAmt" :width="140">
            <template #title>
              <p>
                <span class="warningColor">*</span>
                <span>采购数量</span>
              </p>
            </template>
          </a-table-column>
          <a-table-column data-index="rate" title="税率" :width="150">
            <template #title>
              <p>
                <span class="warningColor">*</span>
                <span>税率</span>
              </p>
            </template>
          </a-table-column>
          <a-table-column data-index="price" :width="150">
            <template #title>
              <div class="flex-c">
                <span class="warningColor">*</span>
                <a-select v-model="priceType" style="width: 110px" size="mini">
                  <a-option :value="1">含税单价</a-option>
                  <a-option :value="0">不含税单价</a-option>
                </a-select>
                <a-popconfirm content="该操作将重新获取报价信息，是否继续？" @ok="setDefaultPrice" type="error">
                  <a-tooltip content="重新获取报价">
                    <icon-refresh class="highlight cursor" style="margin-left: 2px" />
                  </a-tooltip>
                </a-popconfirm>
              </div>
            </template>
          </a-table-column>
          <a-table-column data-index="purchaseAmt1" title="采购金额" :width="80" />
          <a-table-column data-index="singleLaborCosts" :width="150">
            <template #title>
              <div class="flex-c">
                <span class="warningColor">*</span>
                <span>单件工费</span>
                <a-popconfirm @popup-visible-change="globalSingleLaborCostsChange" @ok="updateSingleLaborCosts">
                  <template #content>
                    <p style="margin-bottom: 10px">批量设置单件工费</p>
                    <div class="flex-c">
                      <a-select v-model="globalSingleLaborCostsType" style="width: 100px">
                        <a-option :value="1">固定值</a-option>
                        <a-option :value="2">单价占比</a-option>
                      </a-select>
                      <a-input-number v-model="globalSingleLaborCosts" style="width: 90px" :precision="2" placeholder="" />
                      <span>{{ globalSingleLaborCostsType === 1 ? '￥' : '%' }}</span>
                    </div>
                  </template>
                  <a-button type="text" size="mini" style="margin-left: 4px">批量</a-button>
                </a-popconfirm>
              </div>
            </template>
          </a-table-column>
          <a-table-column data-index="singleLaborCosts1" title="单件成本" :width="80" />
          <a-table-column data-index="singleLaborCosts2" title="合计成本" :width="80" />
          <a-table-column data-index="salesmanName" title="销售员" :width="70" />
          <a-table-column data-index="remark" title="备注" :width="150" />

          <a-table-column title="操作" :width="60" fixed="right">
            <template #cell="{ rowIndex }">
              <a-popconfirm v-if="purchaseItems.length > 1" content="确定是否移除?" @ok="purchaseItems.splice(rowIndex, 1)" type="error">
                <a-button type="text">移除</a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
    <div class="flex-c-c handle-btn-w">
      <a-space>
        <a-button class="gray-outline" size="medium" @click="showModel = true">取消</a-button>
        <a-button type="primary" size="medium" @click="createPlan" :loading="submitLoading">确认</a-button>
      </a-space>
    </div>
    <a-modal v-model:visible="showModel" title-align="start" ok-text="退出" @ok="closePage">
      <template #title>
        <p class="flex-c">
          <icon-exclamation-circle class="warn-icon" />
          <span>确认退出当前界面</span>
        </p>
      </template>
      <p>确认退出【采购下单】界面</p>
      <p>注意：当前内容未保存，关闭后数据无法恢复！</p>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import { useRouter, useRoute } from 'vue-router'
  import { findStayPurchaseItemPage, findSupperList, placePurchaseOrder, findAvailableQuoteList } from '@/api/purchase'
  import { getOrganizesUser } from '@/api/system'
  import dayjs from 'dayjs'
  import { parseJson } from '@/utils'
  import useUserStore from '@/store/modules/user'

  onMounted(() => {
    getPurchaseItemList()
    getSupplierList()
    getUserList()
  })

  const userStore = useUserStore()
  const visitedRouteStore = useVisitedRouteStore()
  const route = useRoute()
  const router = useRouter()
  const showModel = ref(false)
  const tableLoading = ref(false)
  const purchaseItems = ref<Array<any>>([])
  const supplierList = ref<Array<any>>([])
  const userList = ref<Array<any>>([])
  const submitLoading = ref(false)
  const quoteMap = ref<any>({})
  const globalSupplier = ref()
  const priceType = ref(1)
  const globalSingleLaborCostsType = ref(1)
  const globalSingleLaborCosts = ref()
  const purchaseUser = ref<any>({
    id: userStore.userId,
    userName: userStore.userName,
  })

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  //供应商列表
  async function getSupplierList() {
    const res: any = await findSupperList()
    supplierList.value = res?.data || []
  }
  // 获取所有用户列表
  async function getUserList() {
    const res: any = await getOrganizesUser({
      pageNum: 1,
      pageSize: 1000,
    })
    userList.value = res?.data?.records || []
  }
  // 根据选中的id获取购明细列表
  async function getPurchaseItemList() {
    let idsStr = window.localStorage.getItem('purchaseItemIds')
    if (!idsStr) return
    tableLoading.value = true
    const res: any = await findStayPurchaseItemPage({
      pageSize: 100,
      pageNum: 1,
      ids: idsStr,
    })
    tableLoading.value = false
    let list = res?.data?.records || []
    purchaseItems.value = list.map((el: any) => {
      return setItem(el)
    })
    setDefaultPrice()
  }
  // 查询报价列表
  async function getQuoteList() {
    quoteMap.value = {}
    let list: Array<any> = []
    purchaseItems.value.forEach((el: any) => {
      el.childs.forEach((child: any) => {
        if (child?.supplier?.id && el.sku && child.purchaseAmt) {
          list.push({
            purchaseAmt: child.purchaseAmt,
            sku: el.sku,
            spu: el.spu,
            supplierId: child.supplier.id,
          })
        }
      })
    })
    if (!list.length) return
    let res: any = await findAvailableQuoteList({ quoteItems: list })
    let quoteList = res?.data || []
    quoteList.forEach((el: any) => {
      let key = el.sku + el.supplierId
      quoteMap.value[key] = el
    })
  }

  // 设置默认的采购报价
  async function setDefaultPrice(item?: any) {
    await getQuoteList()
    // 全局查询替换
    if (!item) {
      purchaseItems.value.forEach((el: any) => {
        el.childs.forEach((child: any) => {
          changeByQuote(child)
        })
      })
    } else {
      changeByQuote(item)
    }
  }
  // 根据报价修改值
  function changeByQuote(item: any) {
    let detail = quoteMap.value[item.sku + item.supplier?.id] || {}
    // 根据价格类型获取报价的含税或不含税单价
    let priceKey = priceType.value === 1 ? 'taxPrice' : 'price'
    let quotePrice = detail.quoteItems?.[0]?.[priceKey]
    item.moq = detail.moq || 1
    item.rate = quotePrice ? detail.parTaxRate : item.rate
    item.price = quotePrice || item.price
    if (detail.deliveryDays) {
      item.gmtPlanDelivery = dayjs()
        .add(Number(detail.deliveryDays || 0), 'day')
        .format('YYYY-MM-DD')
    }
  }
  // 初始化下单数据
  function setItem(item: any) {
    item.childs = []
    let defaultVal: any = {
      moq: 1,
      sku: item.sku,
      settleType: 1,
      purchaseAmt: item.purchaseStayAmt,
      remark: item.remark,
    }
    if (item.supplierId) {
      defaultVal.supplier = {
        supplierCode: item.supplierCode,
        id: item.supplierId,
        supplierName: item.supplierName,
      }
    }
    item.childs.push(defaultVal)
    return item
  }

  // 关闭界面
  function closePage() {
    visitedRouteStore.removeVisitedRoute(route)
    router.push('/purchase/purchaseManagement/waitingPurchase')
  }
  // 创建采购订单
  async function createPlan() {
    if (!purchaseItems.value.length) {
      Message.error('请最少选择一个采购明细')
      return
    }
    if (!purchaseUser.value?.id) {
      Message.error('请选择采购员')
      return
    }
    let flag = false
    let list: Array<any> = []
    purchaseItems.value.forEach((el: any) => {
      el.childs.forEach((child: any) => {
        let obj = {
          gmtPlanDelivery: child.gmtPlanDelivery,
          purchaseUid: purchaseUser.value.id,
          purchaseUname: purchaseUser.value.userName,
          salesmanName: el.salesmanName,
          salesmanId: el.salesmanId,
          id: el.id,
          price: child.price,
          purchaseAmt: child.purchaseAmt,
          rate: child.rate,
          supplierCode: child.supplier?.supplierCode,
          supplierName: child.supplier?.supplierName,
          supplierId: child.supplier?.id,
          moq: child.moq,
          quotedPrice: child.quotedPrice,
          remark: child.remark,
          singleLaborCosts: child.singleLaborCosts,
          priceType: priceType.value,
          settleType: child.settleType,
        }
        list.push(obj)
        if (!child.supplier?.id || !child.purchaseAmt || !child.gmtPlanDelivery || !(child.price || child.price === 0) || !(child.singleLaborCosts || child.singleLaborCosts === 0)) {
          flag = true
        }
      })
    })
    if (flag) {
      Message.error('请检查必填信息是否完善')
      return
    }
    submitLoading.value = true
    const res: any = await placePurchaseOrder({ purchaseItems: list })
    submitLoading.value = false
    if (res) {
      Message.success('下单成功')
      closePage()
    }
  }
  //设置全局
  async function setGlobal(item: any, key: string, i: number, rowIndex: number) {
    const newVal = item[key]
    purchaseItems.value.forEach((el: any, index: number) => {
      if (index === rowIndex) {
        el.childs.forEach((child: any, j: number) => {
          if (j > i) child[key] = newVal
        })
      } else if (index > rowIndex) {
        el.childs.forEach((child: any) => {
          child[key] = newVal
        })
      }
    })
  }
  // 一键设置供应商
  function updateSupplier() {
    purchaseItems.value.forEach((el: any) => {
      el.childs.forEach((child: any) => {
        child.supplier = globalSupplier.value
      })
    })
    setDefaultPrice()
  }
  // 一键设置单件工费
  function updateSingleLaborCosts() {
    purchaseItems.value.forEach((el: any) => {
      el.childs.forEach((child: any) => {
        let _price = Number(child.price || 0)
        let val = globalSingleLaborCostsType.value === 1 ? globalSingleLaborCosts.value : (Number(globalSingleLaborCosts.value || 0) / 100) * _price
        child.singleLaborCosts = val
      })
    })
  }
  function globalSingleLaborCostsChange() {
    globalSingleLaborCosts.value = null
    globalSingleLaborCostsType.value = 1
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'supplier') {
      return { rowspan: 1, colspan: 13 }
    }
  }
</script>
<style lang="less" scoped>
  .add-purchase-order-wrap {
    height: calc(100vh - @menuHeight);
    display: flex;
    flex-direction: column;
    .header {
      padding: 10px;
      background-color: #fff;
      margin-bottom: 10px;
      font-size: 16px;
    }
    .add-purchase-order-con {
      flex: 1;
      background-color: #fff;
      padding: 20px 10px 0px;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
  }
  .handle-btn-w {
    padding: 10px 0;
    background-color: #fff;
    .arco-btn {
      min-width: 80px;
    }
  }
  .price-type {
    font-size: 12px;
    transform: scale(0.82);
    position: relative;
    left: -4px;
  }
  .urgent {
    font-size: 12px;
    background-color: red;
    color: #fff;
    width: 18px;
    border-radius: 50%;
    line-height: 18px;
    text-align: center;
    transform: scale(0.82);
  }
  .child-w {
    margin: 5px 0;
    .cell {
      padding: 0 8px;
      flex-shrink: 0;
      flex-grow: 1;
      &:first-child {
        padding-left: 0;
      }
      .edit-icon {
        font-size: 16px;
        margin-left: 5px;
        cursor: pointer;
      }
    }
  }
</style>
